package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sort.MapComparator;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class TyphoonDataActivity extends Activity {
	private static final int CURRENT_TYPHOON = Menu.FIRST+1;
	private static final int TYPHOON_LIST = Menu.FIRST+2;
	
	private Map<String,String> typhoon = new HashMap<String,String>();
	private List<Map<String,String>> tracks = new ArrayList<Map<String,String>>();
	private List<Map<String,String>> others = new ArrayList<Map<String,String>>();
	private MapComparator comparator = new MapComparator();	
	private String[] from = { "time", "ydsd", "zxfs", "ydfx","zxqy" };
	private int[] to = {R.id.lbl1,R.id.lbl2,R.id.lbl3,R.id.lbl4,R.id.lbl5};
	private TextView lblTitle;
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.typhoon_data);   //软件activity的布局		
		ActivityStackControlUtil.add(this);
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});

		TextView lblTitle1 = (TextView)findViewById(R.id.lblTitle1);	
		lblTitle1.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				fillListView("time");
			}
		});
		initComponent();
	}

	private void initComponent(){
		dialog = new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			// 处理来自线程的消息,并将线程中的数据设置入listview
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					lblTitle = (TextView)findViewById(R.id.lblTitle);			
					lblTitle.setText(typhoon.get("name")+"(" + typhoon.get("code")+ ")");
					fillListView("");
					dialog.cancel();
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				downloadTyphoonData();	
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);	// 给handle发送的消息
				Looper.loop();
			};

		}.start();
	}
	
	private void downloadTyphoonData() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new TrackHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}	
	}
	
	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String server = CommConstant.Sever.TFDATA_SERVER;
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION +"tftrack.xml");
		} else {
			URL url = new URL(server + "tfdata/TFDetail.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE+"&tfcode="+intent.getStringExtra("code")+"&ename="+intent.getStringExtra("ename"));
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class TrackHandler extends DefaultHandler {
		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("tfinfo".equals(localName)) {
				for (int i = 0; i < attrs.getLength(); i++) {
					typhoon.put(attrs.getLocalName(i), attrs.getValue(i));
				}
			} else if ("trackpos".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				tracks.add(data);
			} else if ("lf".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				others.add(data);
			} else if ("message".equals(localName)) {
				dialog.cancel();
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	
	private void fillListView(String key) {
		if (!"".equals(key)) {
			comparator.setKey(key);
			Collections.sort(tracks, comparator);
		}
		TyphoonDataTableAdapter adapter = new TyphoonDataTableAdapter(this,tracks,R.layout.typhoon_data_item,from,to);
		ListView lstTyphoonList = (ListView) findViewById(R.id.lstTyphoonList);
		lstTyphoonList.setAdapter(adapter);
	}
	
	public class TyphoonDataTableAdapter extends SimpleAdapter {
		private List<Map<String,String>> dataList;
		
		public TyphoonDataTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.dataList = data;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);		 
			int colorPos = position % CommConstant.Config.DEFAULT_TABLE_COLORS.length;
			view.setBackgroundColor(CommConstant.Config.DEFAULT_TABLE_COLORS[colorPos]);
			
			int fs = Integer.parseInt(dataList.get(position).get("zxfs"));
			TextView lbl = (TextView)view.findViewById(R.id.lbldetail);
			if (fs > CommConstant.Typhoon.TYPHOON_FS) {
				lbl.setTextColor(Color.CYAN);
			} else {
				lbl.setTextColor(Color.GREEN);
			}
			
			return view;
		}
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, CURRENT_TYPHOON, 1, R.string.menu_currtyphoon);
		menu.add(0, TYPHOON_LIST, 2, R.string.menu_typhoonlist);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case CURRENT_TYPHOON:
				intent.setClass(getApplicationContext(), TyphoonTrackActivity.class);
				startActivity(intent);
				return true;
			case TYPHOON_LIST:
				intent.setClass(getApplicationContext(), TyphoonListActivity.class);
				startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}